package com.bwton.msx.ccb.ui.auth;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.bwton.msx.ccb.databinding.FragmentRealnameBinding;
import com.bwton.msx.ccb.service.api.ApiServiceManager;
import com.bwton.msx.ccb.service.auth.AuthService;
import com.bwton.msx.ccb.service.user.User;
import com.bwton.msx.ccb.service.user.UserManager;
import com.bwton.msx.ccb.utils.RxViewUtils;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class RealNameFragment extends Fragment {
    private CompositeDisposable disposable = new CompositeDisposable();

    private FragmentRealnameBinding binding;
    private AuthService authService = new AuthService(ApiServiceManager.getAuth());

    private final String TAG = "登录";

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        binding = FragmentRealnameBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        disposable = new CompositeDisposable();
        Disposable userState = UserManager.getInstance().subscribeUserUIState()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .distinctUntilChanged()
                .subscribe(user -> {
                    if (user.isLogin) {
                        binding.inputPhone.setText(user.user.phone);
//                        binding.inputIdCard.setText(user.user.id);
//                        binding.inputName.setText(user.user.name);
//                        binding.inputCardNo.setText(user.user.card);
                        onUserLogin(user.user);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
        disposable.add(userState);

    }

    private void onUserLogin(User user) {
        Disposable smsEvent = RxViewUtils.throttle(binding.btnSms, 10).subscribe(v -> {
            String phone = binding.inputPhone.getEditableText().toString();
            if (phone.length() != 11) {
                Toast.makeText(requireContext(), "手机号不正确!", Toast.LENGTH_SHORT).show();
                return;
            }
            String name = binding.inputName.getEditableText().toString().trim();
            if (name.length() < 2) {
                Toast.makeText(requireContext(), "姓名不正确!", Toast.LENGTH_SHORT).show();
                return;
            }
            String cardNo = binding.inputCardNo.getEditableText().toString().trim();
            if (cardNo.length() < 8) {
                Toast.makeText(requireContext(), "银行卡不正确!", Toast.LENGTH_SHORT).show();
                return;
            }
            String idCardNo = binding.inputIdCard.getEditableText().toString().trim();
            if (idCardNo.length() != 18) {
                Toast.makeText(requireContext(), "身份证不正确!", Toast.LENGTH_SHORT).show();
                return;
            }
            Disposable sms = authService.sendSignSms(phone, user.unionId, "UNIONPAY_UNBQP", "11173318",
                            name, cardNo, idCardNo)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(result -> {
                        binding.textRequest.setText("response:\n" + result.toString());
                        Toast.makeText(requireContext(), result.errmsg, Toast.LENGTH_SHORT).show();
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            throwable.printStackTrace();
                        }
                    });
            disposable.add(sms);
        });
        disposable.add(smsEvent);

        Disposable registerEvent = RxViewUtils.throttle(binding.btnSubmit, 5).subscribe(v -> {
            String phone = binding.inputPhone.getEditableText().toString();
            if (phone.length() != 11) {
                Toast.makeText(requireContext(), "手机号不正确!", Toast.LENGTH_SHORT).show();
                return;
            }
            String sms = binding.inputSms.getEditableText().toString();
            if (sms.length() != 6) {
                Toast.makeText(requireContext(), "验证码不正确!", Toast.LENGTH_SHORT).show();
                return;
            }
            String name = binding.inputName.getEditableText().toString().trim();
            if (name.length() < 2) {
                Toast.makeText(requireContext(), "姓名不正确!", Toast.LENGTH_SHORT).show();
                return;
            }
            String cardNo = binding.inputCardNo.getEditableText().toString().trim();
            if (cardNo.length() < 8) {
                Toast.makeText(requireContext(), "银行卡不正确!", Toast.LENGTH_SHORT).show();
                return;
            }
            String idCardNo = binding.inputIdCard.getEditableText().toString().trim();
            if (idCardNo.length() != 18) {
                Toast.makeText(requireContext(), "身份证不正确!", Toast.LENGTH_SHORT).show();
                return;
            }
            Disposable register = authService.signByCard(phone, user.unionId, "UNIONPAY_UNBQP", "11173318",
                            name, cardNo, idCardNo, sms)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(result -> {
                        binding.textRequest.setText("response:\n" + result.toString());
                        if (result.success) {
                            UserManager.getInstance().update(user1 -> {
                                user1.name = name;
                                user1.card = cardNo;
                                user1.id = idCardNo;
                                user1.state.setEnableRealName(true);
                                user1.state.setEnableSign(true);
                            });
                            NavHostFragment.findNavController(this).navigateUp();
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            throwable.printStackTrace();
                        }
                    });
            disposable.add(register);
        });
        disposable.add(registerEvent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
        disposable.dispose();
        disposable.clear();
    }

}